/*
 * @Author: wangtao
 * @Date: 2020-08-20 14:07:42
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-08-03 17:56:17
 * @Description: 车主端首页
 */

import React from 'react';
import {
  Image,
  NativeModules,
  PixelRatio,
  SafeAreaView,
  StyleSheet,
  TouchableOpacity,
  Text,
  View,
  ScrollView
} from 'react-native';
import {
  iconMainCoffee,
  iconMainGray,
  iconRepairCardEntrance,
  empty04,
  iconChangeWhite,
  carServer,
  iconDriverBao
} from '@/images';
import { msg, Button, XMHeader, _ } from '@/common';
import LinearGradient from 'react-native-linear-gradient';
import {
  mainBgColorLightGray,
  mainBgColorWhite,
  px2dp,
  screenHeight,
  screenWidth,
  fontColorDeepRed,
  fontColorWhite
} from '@/styles';
import Picker from '@/common/picker';
import api from '@/api';
import supply from '@/api/supply';

const { Submit } = Button;

export default class CarOwnerMain extends React.Component {
  static navigationOptions = () => ({
    title: '主页',
    tabBarIcon: ({ focused }) => (
      <Image
        source={focused ? iconMainCoffee : iconMainGray}
        style={{ width: 24, height: 24 }}
      />
    ),
  });

  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      act: 0,
      data: [
        { x: 0, y: 0 },
        { x: 0, y: 1 },
        { x: 0, y: 2 },
        { x: 0, y: 3 },
        { x: 0, y: 4 },

      ],
      type: '',
      isYkcz: false,
      isCar: true,
      car: [],
      selectCar: '全部车辆',
      orderCount: 0
    };
    // this.getOperation();
  }

  addCar() {
    msg.emit('router: goToNext', {
      routeName: 'TruckCert', type: 'add'
    });
  }

  componentDidMount() {
    this.getCar();
  }

  // 获取运单数量
  getWaybillAmount(vehicleNo, time) {
    vehicleNo == '全部车辆' ? vehicleNo = '' : vehicleNo = this.state.selectCar.toString();
    let parame = {
      carNo: vehicleNo,
      time: time
    };
    supply.getWaybillAmountNew(parame).then(res => {
      console.log(res);
      if (res.success) {
        this.setState({
          orderCount: res.data.amount,
        });
      }
    });
  }

  // 获取车辆列表
  getCar() {
    supply.getCarNew().then(res => {
      if (res.success) {
        if (res.data.length > 0) {
          let carList = [];
          res.data.forEach(v => {
            carList.push(v.carNo);
          });
          carList.unshift('全部车辆');
          this.setState({
            isCar: false,
            car: carList
          });
          this.getWaybillAmount('全部车辆', 3);
        } else {
          this.setState({
            isCar: true
          });
        }
      }
    });
  }

  getOperation() {
    NativeModules.BridgeManager.getAppVersion((v) => {
      if (v) {
        api.user.getOperation({ type: Platform.OS, versionNum: v }).then(res => {
          if (res.success && res.data.length > 0) {
            const operationList = res.data;
            let shopArr = operationList.filter((item) => {
              return item.code == 'ykcz';
            }).filter((item) => {
              return item.state == 1;
            });

            if (shopArr.length > 0) {
              this.setState({ isYkcz: true });
            } else {
              this.setState({ isYkcz: false });
            }
          }
        });
      }
    });
  }

  changeData(act) {
    const { selectCar } = this.state;
    this.setState({ act: act });

    switch (act) {
    case 0:
      this.getWaybillAmount(selectCar, 3);
      break;
    case 1:
      this.getWaybillAmount(selectCar, 2);
      break;
    case 2:
      this.getWaybillAmount(selectCar, 1);
      break;
    }

    // if (act == 0) {
    //   var arr = [
    //     { x: 10, y: 0 },
    //     { x: 20, y: 0 },
    //     { x: 30, y: 0 },
    //     { x: 50, y: 0 }
    //   ]
    //   this.setState({ data: arr })
    // }
  }

  choseCar() {
    this.setState({
      modalVisible: true
    });
  }

  _type() {
    let _this = this;
    console.log('zeki', _this.state.type);
    Picker.init({
      pickerTitleText: '选择车辆',
      pickerCancelBtnText: '取消',
      pickerConfirmBtnColor: [186, 145, 74, 1],
      pickerCancelBtnColor: [102, 101, 100, 1],
      pickerConfirmBtnText: '确定',
      selectedValue: ['全部车辆'],
      pickerBg: [255, 255, 255, 1],
      pickerToolBarBg: [255, 255, 255, 1],
      pickerFontColor: [186, 145, 74, 1],
      pickerRowHeight: 40,
      pickerData: this.state.car,
      onPickerConfirm: (pickedValue, pickedIndex) => {
        _this.setState({
          selectCar: pickedValue
        }, () => {
          _this.changeData(0);
          _this.getWaybillAmount(_this.state.selectCar, 3);
        });
      },
      onPickerCancel: (pickedValue, pickedIndex) => {
        console.log('date', pickedValue, pickedIndex);
      },
      onPickerSelect: (pickedValue, pickedIndex) => {
        console.log('date', pickedValue, pickedIndex);
      }
    });
    Picker.show();
  }

  toThousands(num) {
    var num = (num || 0).toString();
    let temp = num.length % 3;
    switch (temp) {
    case 1:
      num = `00${num}`;
      break;
    case 2:
      num = `0${num}`;
      break;
    }
    if (num == 0) {
      return 0;
    }
    return num.match(/\d{3}/g).join(',').replace(/^0+/, '');
  }

  toPage(url) {
    // const { isYkcz } = this.state;
    // if (!url || !isYkcz) {
    //   NativeModules.WindowModule.showWindow(
    //     {
    //       content: '功能等待开放，敬请期待！',
    //       title: '提示',
    //       onlyRightBtn: '1',
    //     },
    //     (e) => { }
    //   );
    //   return;
    // }
    if (!url) {
      NativeModules.WindowModule.showWindow(
        {
          content: '功能等待开放，敬请期待！',
          title: '提示',
          onlyRightBtn: '1',
        },
        (e) => { }
      );
      return;
    }
    msg.emit('router: goToNext', { routeName: url });
  }

  render() {
    const { act, data, modalVisible, isCar, selectCar, orderCount } = this.state;

    const topItem = [
      {
        image: require('../../../images/wl/icon_OilCard.png'),
        label: '充油卡',
        url: 'OilCardPlatform'
      },
      // {
      //   image: require('../../../images/wl/icon_CarInsurance.png'),
      //   label: '购车险',
      //   url: 'InsuranceTab'
      // },
      // {
      //   image: iconRepairCardEntrance,
      //   label: '修理卡',
      //   url: 'WlRepair'
      // },
      {
        image: iconDriverBao,
        label: '敬请期待',
        url: '' // FourStoreEntry
      },
    ];

    return (

      <SafeAreaView>
        {/* <XMHeader
          title='车主服务'
          renderLeft={() => {
            return (
              <TouchableOpacity
                activeOpacity={0.8}
                style={isAndroid ? { paddingVertical: px2dp(14) } :
                  { paddingVertical: px2dp(14), paddingRight: px2dp(40) }}
                onPress={() => {
                  msg.emit('router: back');
                }}
              >
                <Image
                  source={leftBack}
                  style={{ width: 18, height: 18, marginLeft: isAndroid ? 0 : 18 }}
                />
              </TouchableOpacity>
            );
          }}
          renderRight={() => { }}
        /> */}

        <XMHeader
          style={{ borderBottomWidth: 0 }}
          renderLeft={() => {
            return (
              <Image
                source={carServer}
                style={{ width: px2dp(144), height: px2dp(38), marginLeft: px2dp(32) }}
                resizeMode='contain'
              />
            );
          }}
          renderRight={() => {
            return (
              <TouchableOpacity
                style={styles.headerRightContainer}
                activeOpacity={0.8}
                onPress={() => {
                  msg.emit('router: goToNext', {
                    routeName: 'RoleSwitch',
                  });
                }}
              >
                <LinearGradient
                  colors={['#FDCA85', '#EAA448']}
                  style={styles.headerRightContainer}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 0 }}
                >
                  <Text style={styles.headerRightText}>切换身份</Text>
                  <Image
                    source={iconChangeWhite}
                    style={styles.headerChangeImg}
                    resizeMode='contain'
                  />
                </LinearGradient>
              </TouchableOpacity>
            );
          }}
          renderTitle={() => {
            return <Text style={{ color: fontColorDeepRed }}>{_.checkCurrentEnv()}</Text>;
          }}
        />

        <ScrollView style={styles.container}>

          <View style={styles.iconWrap}>

            {
              topItem.map((v, i) => {
                return (
                  <TouchableOpacity style={styles.topIconWrap} onPress={() => { this.toPage(v.url); }}>
                    <Image style={styles.iconImg} source={v.image} />
                    <Text style={styles.tipText}>{v.label}</Text>
                  </TouchableOpacity>
                );
              })
            }

          </View>
          {isCar ? (
            <View style={styles.btnWrap}>
              <Image style={styles.emptyIcon} source={empty04} />
              <Text style={styles.emptyTip}>您还未添加车辆，请前往添加</Text>
              <Submit
                text='+ 添加车辆'
                boxStyle={{
                  borderRadius: px2dp(10),
                  width: px2dp(590),
                  height: px2dp(72),
                  borderRadius: px2dp(80)
                }}
                onClick={() => {
                  this.addCar();
                }}
              />
            </View>
          ) : (
            <View style={{ margin: px2dp(30), borderRadius: px2dp(40) }}>

              <View style={styles.chartBox}>
                <View style={styles.chartWrap}>
                  <View style={styles.carSelect}>
                    <Text style={styles.cirle} />
                    <Text style={styles.carTit} onPress={() => this._type()}>{selectCar}</Text>
                    <Image style={styles.iconDown} source={require('../../../images/wl/icon_down.png')} />
                  </View>
                  <View style={styles.change}>
                    <Text onPress={() => this.changeData(0)} style={[styles.changeItem, act == 0 ? styles.changeItemAct : '']}>本周</Text>
                    <Text onPress={() => this.changeData(1)} style={[styles.changeItem, act == 1 ? styles.changeItemAct : '']}>本月</Text>
                    <Text onPress={() => this.changeData(2)} style={[styles.changeItem, act == 2 ? styles.changeItemAct : '']}>本年</Text>
                  </View>
                </View>

                <View style={styles.ydWrap}>
                  <Text style={styles.ydText}>已完成运单</Text>
                  <View style={styles.nWrap}>
                    <Text style={styles.ydNumber}>{orderCount}</Text>
                    <Text style={styles.dw}>单</Text>
                  </View>
                </View>
              </View>

            </View>

          )}

        </ScrollView>
      </SafeAreaView>

    );
  }
}

const styles = StyleSheet.create({
  container: {
    height: screenHeight,
    width: '100%',
    backgroundColor: mainBgColorLightGray,
  },
  nWrap: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'flex-end',
    justifyContent: 'center'
  },
  dw: {
    marginBottom: px2dp(12),
    color: '#343332',
    marginLeft: px2dp(4)
  },
  ydNumber: {
    textAlign: 'center',
    fontSize: px2dp(60),
    color: '#343332',

  },
  ydText: {
    textAlign: 'center',
    color: '#999896',
    marginBottom: px2dp(20)
  },
  ydWrap: {
    marginLeft: px2dp(30),
    marginRight: px2dp(30),
    borderTopColor: '#F0EFEF',
    borderTopWidth: px2dp(1),
    paddingTop: px2dp(100),
    paddingBottom: px2dp(100)
  },
  emptyIcon: {
    width: px2dp(238),
    height: px2dp(240)
  },
  emptyTip: {
    color: '#999796',
    marginTop: px2dp(60),
    marginBottom: px2dp(60)
  },
  mask: {
    width: screenWidth,
    height: screenHeight,
    backgroundColor: 'rgba(0,0,0,0.2)',
    position: 'absolute',
    left: 0,
    top: 0,
  },
  infoContainer: {
    width: screenWidth,
    maxHeight: 0.5 * screenHeight,
    backgroundColor: mainBgColorWhite,
    position: 'absolute',
    bottom: 0,
    left: 0,
    borderRadius: px2dp(12),
    overflow: 'hidden',
    zIndex: 10,
  },
  header: {
    width: screenWidth,
    height: px2dp(108),
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomWidth: 1 / PixelRatio.get(),
    // borderColor: splitLineColorLightGray,
  },
  cancel: {
    position: 'absolute',
    left: 0,
    top: 0,
    width: 80,
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  change: {
    flexDirection: 'row',
    backgroundColor: '#F0EFEF',
    borderRadius: px2dp(30)
  },
  changeItem: {
    paddingTop: px2dp(10),
    paddingBottom: px2dp(10),
    paddingLeft: px2dp(16),
    paddingRight: px2dp(16),
    color: '#999896',
    margin: px2dp(2),
    fontSize: px2dp(26)
  },
  changeItemAct: {
    backgroundColor: '#fff',
    color: '#343332',
    borderRadius: px2dp(30)
  },
  mItem: {
    paddingLeft: px2dp(6),
    paddingRight: px2dp(6),
    paddingTop: px2dp(3),
    paddingBottom: px2dp(3),

  },
  chartBox: {
    backgroundColor: mainBgColorWhite,
    paddingBottom: px2dp(50),
    borderRadius: px2dp(20),
    marginBottom: px2dp(100)
  },
  chartWrap: {
    marginTop: px2dp(20),
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingLeft: px2dp(20),
    paddingRight: px2dp(20),
    padding: px2dp(20),
    paddingBottom: px2dp(40)
  },
  carSelect: {
    flexDirection: 'row'
  },
  iconWrap: {
    flexDirection: 'row',
    justifyContent: 'center',
    backgroundColor: mainBgColorWhite,
    borderBottomLeftRadius: px2dp(20),
    borderBottomRightRadius: px2dp(20)
  },
  cirle: {
    width: px2dp(12),
    height: px2dp(12),
    backgroundColor: '#EF9730',
    borderRadius: px2dp(20),
    marginTop: px2dp(20),
    marginRight: px2dp(6)
  },
  carTit: {
    color: '#343332',
    fontSize: px2dp(32)
  },
  iconDown: {
    width: px2dp(16),
    height: px2dp(10),
    marginTop: px2dp(18),
    marginLeft: px2dp(8)
  },
  topIconWrap: {
    flex: 1,
    flexDirection: 'column',
    alignItems: 'center',
    textAlign: 'center',
    paddingTop: px2dp(40),
    paddingBottom: px2dp(40)
  },
  tipText: {
    marginTop: px2dp(10)
  },
  btnWrap: {
    alignItems: 'center',
    marginTop: screenHeight / 10
  },
  iconImg: {
    width: px2dp(100),
    height: px2dp(100)
  },
  jisaunWrap: {
    backgroundColor: mainBgColorWhite,
    marginTop: px2dp(20),
    marginBottom: px2dp(1),
    padding: px2dp(20),
    paddingBottom: px2dp(40),
    borderTopLeftRadius: px2dp(20),
    borderTopRightRadius: px2dp(20)
  },
  priceTit: {
    color: '#999896',
    fontSize: px2dp(28),
    marginBottom: px2dp(4)
  },
  priceWrap: {
    flexDirection: 'row'
  },
  danwei: {
    fontSize: px2dp(28),
    marginTop: px2dp(34),
    fontWeight: 'bold',
    color: '#343332'
  },
  money: {
    fontSize: px2dp(60),
    fontWeight: 'bold',
    color: '#343332'
  },
  headerRightContainer: {
    width: px2dp(188),
    height: px2dp(48),
    borderTopLeftRadius: px2dp(24),
    borderBottomLeftRadius: px2dp(24),
    overflow: 'hidden',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  headerRightText: {
    fontSize: px2dp(28),
    fontWeight: 'bold',
    color: fontColorWhite,
  },
  headerChangeImg: {
    width: px2dp(24),
    height: px2dp(24),
    marginLeft: px2dp(8),
  },
});
